package com.bizmda.bizsip.sample.applog.listener;

import cn.hutool.json.JSONObject;
import com.bizmda.bizsip.common.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.stereotype.Service;
import java.util.Map;

/**
 * RabbitMQ接收服务
 */
@Slf4j
@Service
public class AppLogQueueListener {
    public static final String APP_LOG_QUEUE = "queue.bizsip.applog";
    private Jackson2JsonMessageConverter jackson2JsonMessageConverter =new Jackson2JsonMessageConverter();

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = APP_LOG_QUEUE, durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = BizConstant.BIZSIP_LOG_EXCHANGE, type = ExchangeTypes.DIRECT, durable = "true", autoDelete = "false"),
            key = BizConstant.BIZSIP_LOG_ROUTING_KEY))
    public void process(Message message) {
        Map<String,Object> map = (Map<String,Object>)jackson2JsonMessageConverter.fromMessage(message);
        int type = (int)map.get("type");
        BizMessage<JSONObject> inBizMessage = new BizMessage<>((Map) map.get("request"));
        BizMessage<JSONObject> outBizMessage = new BizMessage<>((Map) map.get("response"));
        log.info("\ntype:{}\nrequest:\n{}\nresponse:\n{}",type,
                BizUtils.buildBizMessageLog(inBizMessage),
                BizUtils.buildBizMessageLog(outBizMessage));
        return;
    }
}
